<?php

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-21
 * Time: 18:17:07
 * Info:
 */

namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use Casbin\WebmanPermission\Permission;
use support\lib\Env;

/**
 * 访问控制
 */
class AuthCheckAccess implements MiddlewareInterface
{

    /**
     * @param Request  $request
     * @param callable $handler
     *
     * @return String
     */
    public function process(Request $request, callable $handler): Response
    {
        //检查是否安装
        clearstatcache();
        if ( ! is_file(base_path('/.env'))) {
            return redirect('/install');
        }

        $huicmfConfig     = config('huicmf');
        $session_admin_id = session()->get('session_admin_id');
        $pre_act          = $request->method();

        $controller  = $request->controller;
        $action      = $request->action;
        $currentNode = $request->path();

        //在控制器中控制鉴权
        $class      = new \ReflectionClass($controller);
        $properties = $class->getDefaultProperties();

        //不需要鉴权的控制器
        $noNeedAuthController = $properties['noNeedAuthController'] ?? false;
        //不需要鉴权的方法
        $noNeedAuthAction = $properties['noNeedAuthAction'] ?? [];

        $currentController = str_replace('app\admin\controller\\', "", $controller);

        // 不需要鉴权
        if ($noNeedAuthController || in_array($action, $noNeedAuthAction)) {
            return $handler($request);
        }

        //验证登录
        if ( ! in_array($currentController, $huicmfConfig['no_login_controller']) && ! in_array($currentNode,
                $huicmfConfig['no_login_node'])) {
            if (empty($session_admin_id)) {
                //分割判断是否是插件：plugin，如果是，直接返回json数据【plugin权限验证用】
                $explCurrent = explode("\\", $currentController);
                if (isset($explCurrent[0]) && $explCurrent[0] === 'plugin') {
                    return json(['code' => 0, 'msg' => '请先登录']);
                } else {
                    return error_json('请先登录', '', "/".request()->app.'/login');
                }
            }
        }
        //验证权限
        if ( ! in_array($currentController, $huicmfConfig['no_auth_controller']) && ! in_array($currentNode,
                $huicmfConfig['no_auth_node'])) {
            //获取用户信息
            $adminInfo = cmf_get_admin_info();
            if (empty($adminInfo)) {
                return error_json('登录已过期，请重新登录', '', "/".request()->app.'/login');
            }
            $adminRoleId = ! empty($adminInfo['role_id']) ? $adminInfo['role_id'] : 0;
            if ($adminRoleId != 1) {
                $sub = "admin_role_".$adminRoleId; // 想要访问资源的用户
                $obj = $currentNode; // 将要被访问的资源
                $act = 'GET'; // 用户对资源进行的操作

                //写入权限[案例]
                //Permission::addPolicy($sub, $obj, $act);
                if ( ! Permission::enforce($sub, strtolower($obj), $act)) {
                    return error_json('对不起，您没有该资源访问权限');
                }
            }

            // 判断是否为演示环境
            if (Env::get('HUICMF.IS_DEMO', false) && $request->isPost()) {
                return error_json('演示环境下不允许修改');
            }

        }
        //在登录页且已登录直接跳转
        if ('/'.request()->app.'/login' === $currentNode && $session_admin_id) {
            return success_json('您已登录，无需再次登录', '', '', "/".request()->app.'/index');
        }

        return $handler($request);
    }

}
